package frontend.symtable;

import frontend.symtable.symbol.Symbol;

import java.util.HashMap;
import java.util.Map;
import java.util.Stack;

/**
 * 栈式符号表
 *
 * @author 杨凯伟
 * @date 2024/10/16
 */
public class _SymbolTable extends SymbolTable {
    private final Stack<Map<String, Symbol>> scopeStack = new Stack<>();//每个元素即为一层作用域的符号表

    public _SymbolTable() {
        // 初始化时创建全局作用域
        scopeStack.push(new HashMap<>());
    }

    public boolean contains(String name) {
        for (int i = scopeStack.size() - 1; i >= 0; i--) {
            if (scopeStack.get(i).containsKey(name)) {
                return true;
            }
        }
        return false;
    }

    public void insertSymbol(Symbol symbol) {
        scopeStack.peek().put(symbol.ident, symbol);
        symbol.table = this;
    }

    public Symbol getSymbol(String ident) {
        for (int i = scopeStack.size() - 1; i >= 0; i--) {
            if (scopeStack.get(i).containsKey(ident)) {
                return scopeStack.get(i).get(ident);
            }
        }
        return null;
    }

    public int getCurrentScopeIndex() {
        return scopeStack.size() - 1;
    }

    public void enterScope() {
        scopeStack.push(new HashMap<>());
    }

    public void exitScope() {
        if (!scopeStack.isEmpty()) {
            scopeStack.pop();
        }
    }
}